package edu.stu.recyclerviewscrollbar.scroll

import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Point
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View

class ScrollBar @JvmOverloads constructor(
    context: Context,
    attr: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attr, defStyleAttr) {

    private val RECT_WIDTH = 30f
    private val RECT_HEIGHT = 10f
    private val CORNER_RADIUS = 10f
    private val MARGIN = 5f

    private lateinit var currentPoint: Point

    private val mPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = Color.BLUE
    }

    private var isInit = false

    fun getInitialState() = isInit

    @SuppressLint("Recycle", "DrawAllocation")
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val centerY = height / 2

        if (!::currentPoint.isInitialized) {
            // 初始化 currentPoint 为视图左边中心
            currentPoint = Point((MARGIN + RECT_WIDTH / 2).toInt(), centerY)
        }

        // 绘制圆角矩形
        val left = currentPoint.x - RECT_WIDTH / 2
        val top = currentPoint.y - RECT_HEIGHT / 2
        val right = currentPoint.x + RECT_WIDTH / 2
        val bottom = currentPoint.y + RECT_HEIGHT / 2
        val rect = RectF(left, top, right, bottom)
        canvas.drawRoundRect(rect, CORNER_RADIUS, CORNER_RADIUS, mPaint)

        isInit = true
    }

    fun animateTo(percent: Float) {
        // 计算目标位置的 x 坐标，并进行边界检查
        var targetX = (percent * width).toInt()
        val halfRectWidth = (RECT_WIDTH / 2).toInt()

        // 确保目标位置不会超出视图边界
        targetX = when {
            targetX < halfRectWidth -> (halfRectWidth+MARGIN).toInt()
            targetX > width - halfRectWidth -> (width - halfRectWidth - MARGIN).toInt()
            else -> targetX
        }

        currentPoint = Point(targetX, currentPoint.y)
        invalidate()
    }
}
